<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020-02-21
 * Time: 19:42
 */

namespace Zwwl2016\Cluster;


class ClusterParameters
{
    protected $parameter=array();

    protected $tableName;

    public static function Instance()
    {
        return new ClusterParameters();
    }

    /**
     * @param $parameter $table.$column=$value
     * @return ClusterParameters
     */
    public function where($parameter)
    {
        $a=strpos($parameter,".");
        $b=strpos($parameter,"=");
        $value=substr($parameter,$b+1);
        $value=trim(trim($value),"''");
        if($a===false ||!preg_match('/^\w*$/',substr($parameter,0,$a)))
        {
            $columnName=substr($parameter,0,$b);
            $this->parameter[$columnName]=$value;
            return $this;
        }
        $columnName=substr($parameter,$a+1,$b-$a-1);
        $tableName=substr($parameter,0,$a);
        if (!array_key_exists($tableName,$this->parameter))
        {
            $this->parameter[$tableName]=array();
        }
        $this->parameter[$tableName][$columnName]=$value;
        return $this;
    }

    public function json()
    {
        return json_encode($this->parameter);
    }

    public function getArray()
    {
        return $this->parameter;
    }

    /**
     * @param array $pamameters
     * @return ClusterParameters
     */
    public function setArray(array $pamameters)
    {
        $this->parameter=$pamameters;
        return $this;
    }

    /**
     * @param $name
     * @param $arguments
     * @return ClusterParameters
     * @throws \Exception
     */
    public function __call($name,$arguments)
    {
        $str=Utils::toUnderScore($name);

        if($str=="table")
        {
            if(empty($arguments))
            {
                $this->tableName="";
                return $this;
            }
            $this->tableName=$arguments[0];
            return $this;
        }
        if($this->tableName==null)
        {
            throw new \Exception("table name is null ,please set by \$custerParameter->table(\$tablename) or \$custerParameter->table() for root !");
        }
        if(empty($arguments))
        {
            throw new \Exception("no value is set to column:".$str);
        }
        if(empty($this->tableName))
        {
            $this->parameter[$str]=$arguments[0];
        }
        $this->parameter[$this->tableName][$str]=$arguments[0];
        return $this;
    }

    /**
     * @return ClusterParameters
     */
    public function build()
    {
        return $this;
    }
}